<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      @submit.native.prevent
    >
      <el-form-item label="编码" prop="proOrderId">
        <el-input
          v-model="queryParams.proOrderId"
          filterable
          placeholder="请输入编码"
          @keyup.enter.native="handleQuery"
        ></el-input>
      </el-form-item>
      <el-form-item label="客户" prop="clientId">
        <el-select
          v-model="queryParams.clientId"
          filterable
          placeholder="请选择客户"
          remote
          reserve-keyword
          :remote-method="getListClient"
        >
          <el-option
            v-for="item in clientList"
            :key="item.clientId"
            :label="item.clientName"
            :value="item.clientId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" prop="checkTime">
        <el-date-picker
          align="center"
          style="width: 240px"
          v-model="queryParams.checkTimeObj"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
<el-form-item label="审单时间" prop="orderAuditTime">
        <el-date-picker
          align="center"
          style="width: 240px"
          v-model="queryParams.orderAuditTimeObj"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select
          v-model="queryParams.state"
          placeholder="请选择状态"
          style="width: 100%"
        >
          <el-option
            v-for="item in dict.type.pro_order_state"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
			<el-form-item label="品牌" prop="brandId">
			  <el-select
			    style="width: 100%"
			    v-model="queryParams.brandId"
			    filterable
			    placeholder="请选择品牌"
			  >
			    <el-option
			      v-for="item in brandList"
			      :key="item.brandId"
			      :label="item.brandName"
			      :value="item.brandId"
			    >
			    </el-option>
			  </el-select>
			</el-form-item>
			<el-form-item label="变更单审核" prop="changeReview">
			  <el-select
			    style="width: 100%"
			    v-model="queryParams.changeReview"
			    filterable
			    placeholder="请选择"
			  >
			    <el-option
			      key="2"
			      label="待审核"
			      value="2"
			    />
			    <el-option
			      key="1"
			      label="已审核"
			      value="1"
			    />
			  </el-select>
			</el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['md:order:export']"
          >导出</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="orderList"
      @selection-change="handleSelectionChange"
      :row-class-name="tableRowClassName"
      :max-height="maxHeight"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="订单编号"
        align="center"
        prop="proOrderId"
        width="100"
      >
      </el-table-column>
			<el-table-column
			  label="客户简称"
			  align="center"
			  prop="clientNick"
			  min-width="160"
			/>
      <el-table-column
        label="品牌"
        align="center"
        prop="brandName"
        min-width="100"
      />
      <el-table-column
        label="下单时间"
        align="center"
        prop="checkTime"
        width="180"
      >
       <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.checkTime, "{y}-{m}-{d}") }}</span>
        </template> -->
      </el-table-column>
	  <el-table-column
	    label="审单时间"
	    align="center"
	    prop="orderAuditTime"
	    width="180"
	  >
	    <!-- <template slot-scope="scope">
	      <span v-if="scope.row.state==3 || scope.row.state==4">{{ parseTime(scope.row.checkTime, "{y}-{m}-{d}") }}</span>
	    </template> -->
	  </el-table-column>

	  <el-table-column label="状态" align="center" prop="state">
	    <template slot-scope="{ row }">
	      <el-link
	        type="primary"
	        @click="
	          () => {
	            advanceLog = {
	              show: true,
	              data: {
	                ...row,
	              },
	            };
	          }
	        "
	        >{{ getTypeName(dict.type.pro_order_state, row.state) }}</el-link
	      >
	    </template>
	  </el-table-column>
      <!-- <el-table-column label="商品价格" align="center" prop="commodityPrice" />
      <el-table-column label="邮费" align="center" prop="postage" />
      <el-table-column label="变更费" align="center" prop="changeFee" />
      <el-table-column
        label="总价调整"
        align="center"
        prop="totalPriceAdjustment"
      /> -->
      <el-table-column label="总价" align="center" prop="totalPrice" />
	  <el-table-column label="返利金" align="center" prop="rebateAmount" />
	  <el-table-column label="窗帘账户" align="center" prop="chuangAmount" />
	  <el-table-column label="实付" align="center">
		  <template slot-scope="scope">
		    {{JFpub(scope.row.totalPrice,scope.row.rebateAmount,scope.row.chuangAmount)}}
		  			</template>
	  </el-table-column>
	  <el-table-column label="是否使用返利金" align="center" prop="isUsingRebate" >
		  <template slot-scope="scope">
		    <span v-if="scope.row.isUsingRebate==1">是</span>
			<span v-else>否</span>
			</template>
	  </el-table-column>
	  <el-table-column label="变更单" align="center" prop="changeReview" >
	  		  <template slot-scope="scope">
	  		    <span v-if="scope.row.changeReview==1">已审核</span>
				<span v-else-if="scope.row.changeReview==2">待审核</span>
	  			<span v-else>无</span>
	  			</template>
	  </el-table-column>
      <el-table-column
        label="备注"
        align="center"
        prop="financialRemark"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        min-width="300"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
		  v-if="scope.row.state === '2'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            :disabled="scope.row.state === '4'"
            @click="handleAdvance(scope.row)"
            v-hasPermi="['md:order:edit']"
            >推进</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSplit(scope.row)"
            >明细</el-button>
						<el-button
						  v-if="scope.row.closeStatus==1"
						  size="mini"
						  type="text"
						  icon="el-icon-edit"
						  @click="closeOrder(scope.row)"
						  v-hasPermi="['md:order:edit']"
						  >关闭订单</el-button
						>
			<el-button
			  v-if="scope.row.changeReview==2"
			  size="mini"
			  type="text"
			  icon="el-icon-edit"
			  @click="changedialog(scope.row)"
			  >复审</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
	  :money="money"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
	  layout="slot,total,sizes,prev, pager, next, jumper"
    >
	</pagination>
	<!-- 推进 -->
	<advance-view
	  v-if="advance.show"
	  :show.sync="advance.show"
	  v-bind="advance"
	  @update="getList()"
	></advance-view>

	<split-view
	  v-if="split.show"
	  :show.sync="split.show"
	  v-bind="split"
	></split-view>
	<!-- 推进记录 -->
	<log-view
	  v-if="advanceLog.show"
	  :show.sync="advanceLog.show"
	  v-bind="advanceLog"
	></log-view>
	<!-- 变更订单审核 -->
	<el-dialog
	  :close-on-click-modal="false"
	  title="变更单审核"
	  :visible.sync="opens"
	  width="700px"
	  append-to-body
	>
	  <el-form label-width="100px">
	    <el-row v-if="isUsingRebate">
	      <el-col :span="12">
	        <el-form-item label="使用返利金" prop="tel">
	          <el-input v-model="lfmoney" placeholder="0.00" />
			  <el-input v-model="orderid" style="display: none;"/>
	        </el-form-item>
	      </el-col>
	    </el-row>
	  </el-form>
	  <div slot="footer" class="dialog-footer">
	    <el-button type="primary" @click="submitFormchange">确 定</el-button>
	    <el-button @click="cancels">取 消</el-button>
	  </div>
	</el-dialog>
  </div>
</template>

<script>
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
	closeOrder,
  updatemoneyProOrder,
} from "@/api/asc/order";
import { listClient, getClient } from "@/api/mes/md/client";
import { listBrand } from "@/api/money/brand";
import AdvanceView from "./advance";
import SplitView from "./split";
import commonMix from "@/utils/mixins/common";
import LogView from "./advance/log";

export default {
  name: "Order",
  dicts: ["pro_order_state"],
  mixins: [commonMix],
  components: {
	SplitView,
    AdvanceView,
    LogView,
  },
  data() {
    return {
	  money:0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      clientList: [],
	  isUsingRebate:false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
	  opens: false,
	  lfmoney:0.00,
	  orderid:"",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        orderId: null,
        clientId: null,
        state: null,
        checkTime: null,
        orderAuditTime: null,
        checkTimeObj: null,
        orderAuditTimeObj: null,
      },
      // 表单参数
      form: {
		  'brandId':1,
	  },
      // 表单校验
  //     rules: {
  //       clientId: [
  //         { required: true, message: "请选择客户", trigger: "change" },
  //       ],
  //       checkTime: [
  //         { required: true, message: "请选择下单时间", trigger: "change" },
  //       ],

  //       state: [{ required: true, message: "请选择状态", trigger: "change" }],
  //       otherState: [
  //         { required: true, message: "请选择状态", trigger: "change" },
  //       ],
		// brandId: [
		//   { required: true, message: "请选择品牌", trigger: "change" },
		// ],
  //     },
      room: {
        show: false,
        data: null,
      },
      split: {
        show: false,
        data: null,
      },
      advance: {
        show: false,
        data: null,
      },

      advanceLog: {
        show: false,
        data: null,
      },

      brandList: [
	  ],
    };
  },
  created() {
    this.getList();
    this.getListClient();
    this.getBrandList();
  },
  methods: {
		preciseSubtract(num1, num2) {
	        let result = (num1*100 - num2*100) / Math.pow(10, 2);
	        // 将结果转换回正确的小数形式
	        return Number(result.toFixed(2));
	    },
	  JFpub(a,b,c){
		 
		 let d=this.preciseSubtract(a,b);
		 let e=this.preciseSubtract(d,c);
		return e; 
	  },
    tableRowClassName({ row }) {
      if (row.otherState?.includes("0")) {
        return "success-row";
      } else if (row.otherState?.includes("1")) {
        return "warning-row";
      }
      return "";
    },
	changedialog(row){
		// this.reset();
		this.opens = true;
		this.orderid=row.proOrderId;
		if(row.isUsingRebate==1){
			this.isUsingRebate=true;
		}
	},
	//提交关闭
	closeOrder(row){
		const proOrderIds = row.proOrderId || this.ids;
		closeOrder(proOrderIds).then(({ data }) => {
		  this.$modal.msgSuccess("关闭成功");
		  this.open = false;
		  this.getList();
		});
	},
    getListClient(clientName = "") {
      listClient({
        pageNum: 1,
        pageSize: 100,
		enableFlag:'Y',
        clientName,
        id: "1107",
      }).then(({ rows }) => {
        this.clientList = rows;
      });
    },

    getBrandList() {
      listBrand({
        pageNum: 1,
        pageSize: 500,
      }).then(({ rows }) => {
        this.brandList = rows;
      });
    },
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams,
        checkTimeStart: this.queryParams.checkTimeObj?.[0] || null,
        checkTimeEnd: this.queryParams.checkTimeObj?.[1] || null,
        orderAuditTimeStart: this.queryParams.orderAuditTimeObj?.[0] || null,
        orderAuditTimeEnd: this.queryParams.orderAuditTimeObj?.[1] || null,
      };
      delete params.checkTimeObj;
      delete params.orderAuditTimeObj;
      listOrder(params).then((response) => {
        this.orderList = response.rows;
        this.total = response.total;

		let filteredStr = response.msg.replace(/[{}]/g, '');
		 filteredStr = filteredStr.replace("totalRebateAmount", '返利金');
     filteredStr = filteredStr.replace("totalChuangAmount", '窗帘账户');
		 filteredStr = filteredStr.replace("totalPrice", '总价');
	    let rs = filteredStr.split(",");

		let flmoney=rs[0].split("=")[1]
		let money=rs[1].split("=")[1]
    let chuangmoney=rs[2].split("=")[1]
		let k=this.preciseSubtract(money,flmoney)
		let sfmoney=this.preciseSubtract(k,chuangmoney)
		console.log(sfmoney)
		filteredStr=filteredStr+"，实付="+sfmoney
		this.money = filteredStr;
        this.loading = false;
      });
    },
    handleClientChange() {
      const { province, city, district, address, tel } = this.clientList?.find(
        (e) => e.clientId === this.form.clientId
      );
      this.form.address = `${province || ""}${city || ""}${district || ""}${
        address || ""
      }`;
      this.form.tel = tel;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
	cancels() {
	  this.opens = false;
	  this.lfmoney=0.00;
	  this.reset();
	},
    // 表单重置
  //   reset() {
  //     this.form = {
  //       otherState: ["2"],
		// isUsingRebate:[],
		// brandId:1,
  //       tel: null,
  //       proOrderId: null,
  //       clientId: null,
  //       clientName: null,
  //       preparedBy: null,
  //       preparedByName: null,
  //       checkTime: this.parseTime(new Date(), "{y}-{m}-{d}"),
  //       orderAuditTime: this.parseTime(
  //         new Date().valueOf() + 24 * 3600 * 10000,
  //         "{y}-{m}-{d}"
  //       ),
  //       remark: null,
  //       address: null,
  //       state: "0",
  //       commodityPrice: null,
  //       postage: null,
  //       changeFee: null,
  //       totalPriceAdjustment: null,
  //       totalPrice: null,
  //     };
  //     this.resetForm("form");
  //   },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.checkTimeObj = null;
      this.queryParams.orderAuditTimeObj = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.proOrderId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 获取数据
    async getOrderData(proOrderId) {
      const { data } = await getOrder(proOrderId);
      return data;
    },

    // 推进
    handleAdvance(row) {
      this.advance = {
        show: true,
        data: {
          ...row,
        },
      };
    },

    /** 拆单 */
    handleSplit(row) {
      this.split = {
        show: true,
        data: {
          ...row,
        },
      };
    },
	submitFormchange(){
		  let orderid= this.orderid;
		  let money= this.lfmoney;
		updatemoneyProOrder(orderid,money).then(({ data }) => {
		  this.$modal.msgSuccess("审核成功");
		  this.opens = false;
		  this.getList();
		});
	},
    handleCopyChange(data) {
      this.goPages(data);
    },
    /** 跳转绑定房间 */
    async goPages(id) {
      const data = await this.getOrderData(id);
      this.handleRoom(data);
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "md/order/export",
        {
          ...this.queryParams,
		  orderAuditTimeStart: this.queryParams.orderAuditTimeObj?.[0] || null,
		  orderAuditTimeEnd: this.queryParams.orderAuditTimeObj?.[1] || null,
        },
        `order_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep {
  .el-form-item {
    input {
      text-align: left;
    }
  }
  .el-table .warning-row {
    background: #b3d8ff;
  }

  .el-table .success-row {
    background: #fbc4c4;
  }
}
</style>
